/*
   Copyright (c) 2015 Mizar Tools Contributors (mizartools.org)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
/*  Contributors : 
 *  Marco Riccardi
 *  2015-02-07 - initial implementation
 *
 */
package org.mizartools.example.ui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.LinkedList;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.mizartools.dli.DecodedLibraryItem;
import org.mizartools.dli.DliException;
import org.mizartools.dli.utility.DirectoryFactory;
import org.mizartools.dli.utility.ItemFactory;
import org.mizartools.dli.utility.SchemeId;
import org.mizartools.dli.utility.TheoremId;
import org.mizartools.system.Article;
import org.mizartools.system.ArticleFactory;
import org.mizartools.system.IClusterRegistration;
import org.mizartools.system.IElement;
import org.mizartools.system.ListArticleFile;
import org.mizartools.system.utility.ConstructorsSignature;
import org.mizartools.system.utility.DefinientiaSignature;
import org.mizartools.system.utility.IdentifyRegistrationsSignature;
import org.mizartools.system.utility.NotationsSignature;
import org.mizartools.system.utility.PropertyRegistrationsSignature;
import org.mizartools.system.utility.ReductionRegistrationsSignature;
import org.mizartools.system.utility.RegistrationsSignature;
import org.mizartools.system.utility.SchemesSignature;
import org.mizartools.system.utility.TheoremsSignature;
import org.mizartools.system.xml.Constructor;
import org.mizartools.system.xml.Definiens;
import org.mizartools.system.xml.Identify;
import org.mizartools.system.xml.Pattern;
import org.mizartools.system.xml.Property;
import org.mizartools.system.xml.Reduction;
import org.mizartools.system.xml.Scheme;
import org.mizartools.system.xml.Theorem;
import org.mizartools.utility.UtilityFile;

@SuppressWarnings("serial")
public class UtilityDliCreateArticlesPanel extends JPanel {

	private JTextArea textArea;
	private JScrollPane scroller;
	private JProgressBar progressBar;
	private JButton button;
	private UtilityDliFrame utilityDliFrame;

	public UtilityDliCreateArticlesPanel(UtilityDliFrame utilityDliFrame){
		super();
		this.utilityDliFrame = utilityDliFrame;
    	setLayout(new BorderLayout());
		setPreferredSize(new Dimension(500, 150));
		button = new JButton();
		AbstractAction action =  new AbstractAction() { 
	 	    public void actionPerformed(ActionEvent e) {
	 	    	textArea.setText(Calendar.getInstance().getTime().toString()+"\n\n");
	 			Job job = new Job();
	 			Thread thread = new Thread(job);
	 			thread.start();
	 	    } 
	 	}; 
	 	button.setAction(action);
	 	button.setMaximumSize(getMaximumSize());
	 	button.setText("Start");
		add(button, BorderLayout.NORTH);
		textArea = new JTextArea();
		textArea.setEditable(false);
        scroller = new JScrollPane();
		scroller.getViewport().add(textArea);
		add(scroller, BorderLayout.CENTER);
		progressBar = new JProgressBar();
		add(progressBar, BorderLayout.SOUTH);
		
	}
	
	private class Job implements Runnable {

		@Override
		public void run() {
			button.setEnabled(false);
			LinkedList<String> articleList = ListArticleFile.getAllArticleList();
	    	progressBar.setMaximum(articleList.size()+1);
	    	progressBar.setValue(0);
	    	progressBar.setIndeterminate(false);
	    	Article article = null;
	    	String articleName = null;
	    	String fileName = null;
	    	int progress = 0;
			try {
				String dliPath = DirectoryFactory.getDliArticlesDirectory().getAbsolutePath();
				boolean error = false;
		    	for (String aid : articleList){
		    		if (progress++ < 0) continue;
		    		if (!error){
			    		article = ArticleFactory.getInstance().getArticle(aid);
			    		articleName = article.getAid().toLowerCase();
						fileName = articleName + ".dli";
						textArea.append((aid+" ["+progress+"]        ").substring(0,15)+" : ");
						error = createDli(dliPath, article);
						if (error) {
							textArea.append("[ERROR EXPORT] ["+dliPath+File.separator+fileName+"]");
						} else {
							textArea.append("[OK] ");
						}
						textArea.append("\n");
			    		textArea.repaint();
			    		textArea.setCaretPosition(textArea.getText().length()-1);
				    	progressBar.setValue(progress);
				    	progressBar.repaint();
				    	if (utilityDliFrame.isClosed()) {
				    		error = true;
				    	}
		    		}
		    	}
			} 
			catch (Exception e) {
				textArea.append("\n");
	    		textArea.append(fileName);
	    		textArea.append(" -> Error");
				textArea.append("\n");
	    		textArea.append(e.getMessage());
	    		textArea.append(e.getStackTrace().toString());
				textArea.append("\n");
	    		textArea.repaint();
	    		textArea.setCaretPosition(textArea.getText().length()-1);
			}
			textArea.append("\n");
			textArea.repaint();
			textArea.setCaretPosition(textArea.getText().length()-1);
	    	progressBar.setValue(0);
			button.setEnabled(true);
		}
		
	}
	
	boolean createDli(String directory, Article article) throws IOException, DliException {
		
		boolean error = false;
		StringBuffer buffer = new StringBuffer("");
			
    	String articleName = article.getAid().toLowerCase();
		if (article.hasNotations()) {
    	    LinkedList<Pattern> patternList = article.getNotations().getPatternList();
    		NotationsSignature notationsSignature = article.getNotationsSignature();
    		for (Pattern pattern : patternList ){
    			DecodedLibraryItem decodedLibraryItem = ItemFactory.getItem(notationsSignature, pattern);
    	    	if (directory != null) {
    	    		buffer.append(decodedLibraryItem.toString());
    	    		buffer.append("\n");
    	    	}
   			}			    			
   		}
		if (article.hasConstructors()){
	    	LinkedList<Constructor> constructorList = article.getConstructors().getConstructorList();
			ConstructorsSignature constructorsSignature = article.getConstructorsSignature();
			for (Constructor constructor :constructorList ){
				DecodedLibraryItem decodedLibraryItem = ItemFactory.getItem(constructorsSignature, constructor);
    	    	if (directory != null) {
					buffer.append(decodedLibraryItem.toString());
					buffer.append("\n");
    	    	}
			}
		}
		if (article.hasDefinientia()){
			int relativeNr = 0;
			int nrDefiniens = 0;
	    	LinkedList<Definiens> definiensList = article.getDefinientia().getDefiniensList();
			DefinientiaSignature definientiaSignature = article.getDefinientiaSignature();
			for (Definiens definiens : definiensList ){
				nrDefiniens++;
				relativeNr = definiens.getDefnr() - nrDefiniens;
				DecodedLibraryItem decodedLibraryItem = ItemFactory.getItem(definientiaSignature, definiens, relativeNr);
    	    	if (directory != null) {
					buffer.append(decodedLibraryItem.toString());
					buffer.append("\n");
    	    	}
			}
		}
		if (article.hasRegistrations()) {
	    	LinkedList<IClusterRegistration> clusterRegistrationList = article.getRegistrations().getIClusterRegistrationList();
			RegistrationsSignature registrationSignature = article.getRegistrationsSignature();
			for (IClusterRegistration iClusterRegistration : clusterRegistrationList){
				DecodedLibraryItem decodedLibraryItem = ItemFactory.getItem(registrationSignature, iClusterRegistration);
    	    	if (directory != null) {
					buffer.append(decodedLibraryItem.toString());
					buffer.append("\n");
    	    	}
			}			    			
		}
		if (article.hasIdentifyRegistrations()){
	    	LinkedList<Identify> identifyList = article.getIdentifyRegistrations().getIdentifyList();
			IdentifyRegistrationsSignature identifyRegistrationsSignature = article.getIdentifyRegistrationsSignature();
			for (Identify identify : identifyList){
				DecodedLibraryItem decodedLibraryItem = ItemFactory.getItem(identifyRegistrationsSignature, identify);
    	    	if (directory != null) {
					buffer.append(decodedLibraryItem.toString());
					buffer.append("\n");
    	    	}
			}
		}
		if (article.hasReductionRegistrations()){
	    	LinkedList<Reduction> reductionList = article.getReductionRegistrations().getReductionList();
			ReductionRegistrationsSignature reductionRegistrationsSignature = article.getReductionRegistrationsSignature();
			for (Reduction reduction : reductionList){
				DecodedLibraryItem decodedLibraryItem = ItemFactory.getItem(reductionRegistrationsSignature, reduction);
    	    	if (directory != null) {
					buffer.append(decodedLibraryItem.toString());
					buffer.append("\n");
    	    	}
			}
		}
		if (article.hasPropertyRegistrations()){
	    	LinkedList<Property> propertyList = article.getPropertyRegistrations().getPropertyList();
	    	PropertyRegistrationsSignature propertyRegistrationsSignature = article.getPropertyRegistrationsSignature();
			for (Property property : propertyList){
				DecodedLibraryItem decodedLibraryItem = ItemFactory.getItem(propertyRegistrationsSignature, property);
    	    	if (directory != null) {
					buffer.append(decodedLibraryItem.toString());
					buffer.append("\n");
    	    	}
			}
		}
		if (article.hasTheorems()) {
	    	LinkedList<Theorem> theoremList = article.getTheorems().getTheoremList();
			TheoremsSignature theoremsSignature = article.getTheoremsSignature();
			TheoremId theoremId = new TheoremId();
			TheoremId theoremIdDef = new TheoremId();
			for (Theorem theorem : theoremList ){
				DecodedLibraryItem decodedLibraryItem = ItemFactory.getItem(theoremsSignature, theorem, theoremId, theoremIdDef);
				if (directory != null) {
					buffer.append(decodedLibraryItem.toString());
					buffer.append("\n");
    	    	}					
			}
		}
		if (article.hasSchemes()) {
	    	LinkedList<IElement> elementList = article.getSchemes().getElementList();
			SchemesSignature schemesSignature = article.getSchemesSignature();
		 	SchemeId schemeId = new SchemeId();
			for (IElement element : elementList){
				if (element instanceof Scheme) {
    				Scheme scheme = (Scheme) element;
    				DecodedLibraryItem decodedLibraryItem = ItemFactory.getItem(schemesSignature, scheme, schemeId);
        	    	if (directory != null) {
	    				buffer.append(decodedLibraryItem.toString());
	    				buffer.append("\n");
        	    	}
				} else {
					schemeId.increment();
				}
			}
		}
		
    	if (directory != null) {
    		File destinationFile = new File(directory, articleName+".dli");
    		error = !UtilityFile.writeFile(destinationFile, buffer.toString());
    	}	

		return error;
	}

	
}
